package com.ly.blog_user.security;

import com.ly.blog_common.constant.Constant;
import com.ly.blog_common.response.BlogException;
import com.ly.blog_common.response.BlogResponseStatus;
import com.ly.blog_common.security.JwtUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 用户权限处理器- 自定义JWT处理
 * @author ly create at 2021/6/3 - 17:01
 **/
public class JwtAuthenticationProvider extends DaoAuthenticationProvider {

    public JwtAuthenticationProvider(UserDetailsService userDetailsService) {
        setUserDetailsService(userDetailsService);
    }

    //额外的权限检查 - 检测输入密码和获取用户密码是否一致 -- 添加用户检查，不在获取用户时检测，有异常拦截。
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {

        JwtUserDetails jwtUserDetails = (JwtUserDetails) userDetails;
        if (jwtUserDetails.getUser() == null) {
            throw new BlogException(BlogResponseStatus.USER_LOGIN_USERNAME_NO_EXIST);
        }

        if (authentication.getCredentials() == null) {
            throw new BlogException(BlogResponseStatus.USER_LOGIN_PASSWORD_NO_EXIST);
        }

        String presentedPassword = authentication.getCredentials().toString(); //用输入密码
        String salt = jwtUserDetails.getSalt();
        // 覆写密码验证逻辑 +++++ 增加逻辑判定，邮箱登录时，不需要密码校验
        if (!Constant.LOGIN_EMAIL.equals(presentedPassword) && !new MyBCryptPasswordEncoder().matches(presentedPassword,salt, userDetails.getPassword())) {
            throw new BlogException(BlogResponseStatus.USER_LOGIN_PASSWORD_ERROR);
        }

        //账号锁定
        if(jwtUserDetails.getUser().getStatus() == 0){
            throw new BlogException(BlogResponseStatus.USER_LOGIN_LOCKED);
        }
    }

}
